//
//  XPUserAccountViewModel.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/12.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

class XPUserAccountViewModel: NSObject {
    
    static let defaultUserAccount = XPUserAccountViewModel()
    
    var userAccount: XPUserAccount?
    
    // MARK: - 一实例化该类就重写init方法来获取账户信息,就不用再次去获取网络数据
    override init() {
        super.init()
        userAccount = XPUserAccount.loadUserInfo()
    }
    
    var accessToken: String? {
        guard let myToken = userAccount?.access_token else {
            return nil
        }
        
        if let result = userAccount?.expiresTime?.compare(NSDate()) where result == NSComparisonResult.OrderedDescending {
            return myToken
        }else{
            return nil
        }
    }
    
    var isLogin: Bool {
        return accessToken != nil
    }
    // MARK: - 获取accessToken的接口
    func userAccessToken(code: String, complete:(isSucess:Bool)->()) {
        XPNetworkTool.sharedTools.requestAccessToken(code, resultClosure: { (successResult, errorResult)->() in
            if errorResult != nil {
                print("获取accesstoken请求错误,原因:\(errorResult)")
                return
            }
            guard let dict = successResult as? [String: AnyObject] else{
                return
            }
            
            let userAccount = XPUserAccount(dict: dict)
            self.userInfo(userAccount, complete: complete)
        })
    }
    
    private func userInfo(userAccount: XPUserAccount, complete:(isSucess:Bool)->()) {
        XPNetworkTool.sharedTools.requestUserInfo(userAccount, resultClosure: { (successResult, errorResult)->() in
            if errorResult != nil {
                print("获取用户数据请求失败,原因:\(errorResult)")
                return
            }
            guard let dict = successResult as? [String: AnyObject] else{
                return
            }
            
            userAccount.name = dict["name"] as? String
            userAccount.avatar_large = dict["avatar_large"] as? String
            
            self.userAccount = userAccount
            
            let result = userAccount.saveUserInfo()
            complete(isSucess: result)
        })
    }
}
